"""Script for removing files with names that match a pattern.
"""
import os.path
import optparse
import sys
import re

import aktoolbox


def _error(msg):
    print >> sys.stderr, msg
    sys.exit(1)

def _info(msg):
    print "* %s" % (msg,)
    sys.stdout.flush()

def _warn(msg):
    print sys.stderr, "* %s" % (msg,)
    sys.stderr.flush()


def main():
    # Don't use %prog, since if we install with distribute, the program name
    # may come out as akclean-script.py
    clparser = optparse.OptionParser(usage="""\
akclean [options] <pattern> [directory]

Search an optionally specified directory (default: current directory) for files
matching a Perl-style regex and remove them.\
""")
    clparser.add_option("-n", "--dry-run", action="store_true", default=False,
            help="Only simulate file deletion")
    clparser.add_option("--version", action="store_true", default=False,
            help="Print the version number and exit")
    global _opts
    _opts, args = clparser.parse_args()
    
    if _opts.version:
        print "AKClean %s" % (aktoolbox.__version__,)
        sys.exit(0)

    try:
        pattern, search_dir = args
    except ValueError:
        try:
            pattern, = args
            search_dir = "."
        except ValueError:
            clparser.error("Wrong number of arguments")

    def delete_file(fpath):
        _info("Deleting '%s'" % (fpath,))
        if not _opts.dry_run:
            try:
                os.remove(fpath)
            except EnvironmentError, err:
                _warn("Can't delete file: %s" % (err,))

    re_fname = re.compile(pattern)
    for dpath, dnames, fnames in os.walk(search_dir):
        for fname in fnames:
            if re_fname.match(fname):
                delete_file(os.path.join(dpath, fname))
            else:
                #assert "~" not in fname, fname
                pass

if __name__ == "__main__":
    main()
